package pool;

import java.util.Properties;
import java.util.ResourceBundle;
import java.util.TimerTask;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 线程池的提交装置，单例模式去创建线程池，并作为提交任务的一个接口
 * @author Karl
 * @Date 2023/1/1 - 16:03
 */
public class ThreadManager {

    // 核心线程池大小
    private int corePoolSize = 50;

    // 最大可创建的线程数
    private int maxPoolSize = 200;

    // 队列最大长度
    private int queueCapacity = 1000;

    // 线程池维护线程所允许的空闲时间
    private int keepAliveSeconds = 300;



    private static volatile ThreadManager instance;

    public static ThreadManager getManager(){
        if(instance==null){
            synchronized (ThreadManager.class){
                if(instance==null){
                    instance = new ThreadManager();
                }
            }
        }
        return instance;
    }

    private ThreadPoolExecutor executor;

    private ThreadManager(){
        ResourceBundle bundle = ResourceBundle.getBundle("configuration");
        if (bundle.containsKey("pool.corePoolSize")) {
            corePoolSize = Integer.parseInt(bundle.getString("pool.corePoolSize"));
        }
        if (bundle.containsKey("pool.maxPoolSize")) {
            maxPoolSize = Integer.parseInt(bundle.getString("pool.maxPoolSize"));
        }
        if (bundle.containsKey("pool.queueCapacity")) {
            queueCapacity = Integer.parseInt(bundle.getString("pool.queueCapacity"));
        }
        if (bundle.containsKey("pool.keepAliveSeconds")) {
            keepAliveSeconds = Integer.parseInt(bundle.getString("pool.keepAliveSeconds"));
        }
        executor = new ThreadPoolExecutor(corePoolSize,maxPoolSize,keepAliveSeconds, TimeUnit.MILLISECONDS,new LinkedBlockingDeque<>(queueCapacity));
    }


    public void execute(Runnable task){
        executor.execute(task);
    }


}
